import axios from "axios";
import Message from "../utils/Message";
// 创建 axios 实例

const instance = axios.create({
  withCredentials: true, // 允许携带凭证
  baseURL: import.meta.env.VITE_BASE_URL + 'api', // 基础 URL
  timeout: 8 * 1000, // 请求超时时间
});

// 请求拦截器：自动添加 token
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.authorization = token; // 添加 token 到请求头
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器：统一处理错误
instance.interceptors.response.use(
  (response) => {
    // 如果返回数据形如 {message: "xxx"}，则弹出提示
    if (response.data.message && Object.keys(response.data).length === 1) {
      Message.success(response.data.message);
    }
    return response.data; // 直接返回响应数据
  },
  (error) => {
    const { response } = error;
    console.error("响应错误:", response);
    // 服务器异常
    if (response?.data.error) {
      Message.error(response.data.error);
    }
    // 普通错误
    else if (response?.data.message) {
      Message.warning(response.data.message);
    }
    // 其他错误message
    else {
      Message.error(error.message || "网络异常，请稍后重试");
    }

    return Promise.reject(error);
  },
);


// 封装请求方法
const request = {
  post: async (url, data) => instance.post(url, data),
  get: async (url, params) => instance.get(url, { params }),
  put: async (url, data) => instance.put(url, data),
  patch: async (url, data) => instance.patch(url, data),
  del: async (url, data) => instance.delete(url, { data }),
  getBlob: async (url) => instance.get(url, { responseType: 'blob' }),
};

export default request;
